import React from "react"
import {compose, lifecycle, withHandlers, withState} from "recompose"
import {del, get} from "server"
import {pageSetting} from "project-config"
import {message, Modal} from "antd"
import {rootPath} from "../../../../shared/init"
import { ExclamationCircleOutlined } from '@ant-design/icons'

const favoriteCompose = compose(
  withState('dataSource', '$dataSource', []),
  withState('loading', '$loading', false),
  withState('selectedRowKeys', '$selectedRowKeys', []),
  withState('pagination', '$pagination', Object.assign({}, pageSetting)),
  withState('searchKey', '$searchKey', ''),
  withHandlers({
    getPageData: ({$pagination, pagination, $loading, $dataSource, $selectedRowKeys}) => {
      return (param, pageSize, pageNum) => {
        $loading(true)
        get(`/favorite/page/${pageSize || 10}/${pageNum || 1}`, param)
          .then(page => {
            $dataSource(page.pageData)
            $selectedRowKeys([])
            pagination.total = page.total
            pagination.pageSize = pageSize || 10
            pagination.current = pageNum || 1
            $pagination(Object.assign({}, pagination))
          }).finally(() => {
          $loading(false)
        })
      }
    }
  }),
  withHandlers({
    onFastSearch: ({$searchKey, getPageData}) => {
      return (key) => {
        $searchKey(key)
        getPageData({code: key})
      }
    }
  }),
  withHandlers({
    onPageChange: ({searchKey, getPageData}) => {
      return (page) => {
        getPageData({code: searchKey || ''}, page.pageSize, page.current)
      }
    },
    delBatch: ({selectedRowKeys, getPageData, searchKey}) => {
      return () => {
        const delAction = () => del(`/favorite`, {ids: selectedRowKeys})
          .then(() => {
            getPageData(searchKey ? {code: searchKey} : {})
            message.success(`成功删除${selectedRowKeys.length}条记录`)
          })
        Modal.confirm({
          icon: <ExclamationCircleOutlined />,
          title: '确认删除',
          content: <div>确认要删除以下 <b className={'line-stress'}>{selectedRowKeys.length}</b> 项记录吗?</div>,
          onOk: delAction
        })
      }
    },
    onDel: ({getPageData, searchKey}) => {
      return (row) => {
        del(`/favorite`, {ids: [row.id]})
          .then(() => {
            getPageData(searchKey ? {code: searchKey} : {})
            message.success(`成功删除${row.clothingCode}`)
          })
      }
    },
    onView: ({history}) => {
      return (row) => {
        history.push(`/${rootPath}/library/buy/${row.clothingId}`)
      }
    }
  }),
  lifecycle({
    componentDidMount() {
      const {getPageData} = this.props
      getPageData()
    }
  })
)

export default favoriteCompose